package com.lehuowujie.lehuomarket.viewpagerindicator;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.CornerPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lehuowujie.lehuomarket.R;

import java.util.List;

/**
 * Created by EvangelineLy on 2017/1/14.
 */
public class ViewPagerIndicator extends LinearLayout {

    /**
     * 默认textView的背景色
     */
//    private static final int NORMAL_TEXT_BACKGROUND = 0xEE000000;

    /**
     * 默认字体的颜色
     */
    private static final int NORMAL_TEXT_COLOR = 0x77FFFFFF;
    /**
     * 默认字体的大小
     */
    private static final int NORMAL_TEXT_SIZE = 16;

    /**
     * 默认底部指示器的颜色
     */
    private static final int NORMAL_INDICATOR_COLOR = 0xFF00FF00;

    /**
     * 默认三角形的颜色
     */
    private static final int NORMAL_TRIANGLE_COLOR = 0xFFFFFFFF;

    /**
     * 默认指示器的高度
     */
    private static final int NORMAL_INDICATOR_HEIGHT = 10;

    /**
     * 选中字体的颜色
     */
    private static final int SELECT_TEXT_COLOR = 0xFFFFFFFF;

    /**
     * 选中字体的大小
     */
    private static final int SELECT_TEXT_SIZE = 18;

    /**
     * 选中项的textView的背景色
     */
//    private static final int SELECT_TEXT_BACKGROUND = 0x77FFFFFF;

    /**
     * 默认显示的标签数量
     */
    private static final int DEFAULT_VISIBLE_TAB_COUNT = 4;

    private static final float RADION_TRIANGLE_WIDTH_AND_HEIGHT = 1 / 6F;

    private int mNormalTextColor = NORMAL_TEXT_COLOR;

    private int mNormalTextSize = NORMAL_TEXT_SIZE;

//    private int mNormalTextBackground = NORMAL_TEXT_BACKGROUND;

    private int mNormalIndicatorColor = NORMAL_INDICATOR_COLOR;

    private int mNormalIndicatorHeight = NORMAL_INDICATOR_HEIGHT;

    private int mSelectTextColor = SELECT_TEXT_COLOR;

    private int mSelectTextSize = SELECT_TEXT_SIZE;

    private int mNormalTriangleColor = NORMAL_TRIANGLE_COLOR;

//    private int mSelectTextBackground = SELECT_TEXT_BACKGROUND;

    //----------------------------------------------------------------

    private Paint mPaint;

    //绘制三角形的类
    private Path mPath;
    /**
     * 三角形的高度
     */
    private int mTriangleWidth;

    /**
     * 三角形的宽度
     */
    private int mTriangleHeight;

    /**
     * 三角形的最大宽度
     */
    private int mTriangleMaxWidth;

    /**
     * 初始位移位置
     */
    private int mFirstTranslationX;

    /**
     * 手指滑动时移动的距离
     */
    private int mTranslationX;

////    如果是自适应大小
//    /**
//     * 下划线的起始位置
//     */
//    private int mTranslationStartX;
//
//    /**
//     * 下划线的结束位置
//     */
//    private int mTranslationEndX;
//
//    /**
//     * 当前指示器的下标
//     */
//    private int mCurrentPosition = 0;

    /**
     * 选择是下划线样式还是三角形样式
     * 0  --- 下划线
     * 1  --- 三角形
     */
    private int indicatorType = 0;

    private int mVisibleTabCount = DEFAULT_VISIBLE_TAB_COUNT;

    private ViewPager mViewPager;

    /**
     * 标签集合
     */
    private List<String> mTitles;

    public ViewPagerIndicator(Context context) {
        this(context, null);
    }

    public ViewPagerIndicator(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ViewPagerIndicator);
        mNormalIndicatorHeight = a.getInt(R.styleable.ViewPagerIndicator_tab_indicator_height, NORMAL_INDICATOR_HEIGHT);
        mNormalIndicatorColor = a.getInt(R.styleable.ViewPagerIndicator_indicator_color, NORMAL_INDICATOR_COLOR);
        mNormalTextColor = a.getInt(R.styleable.ViewPagerIndicator_normal_text_color, NORMAL_TEXT_COLOR);
        mNormalTextSize = a.getInt(R.styleable.ViewPagerIndicator_normal_text_size, NORMAL_TEXT_SIZE);
        mSelectTextColor = a.getInt(R.styleable.ViewPagerIndicator_select_text_color, SELECT_TEXT_COLOR);
        mSelectTextSize = a.getInt(R.styleable.ViewPagerIndicator_select_text_size, SELECT_TEXT_SIZE);
        mVisibleTabCount = a.getInt(R.styleable.ViewPagerIndicator_visible_count, DEFAULT_VISIBLE_TAB_COUNT);
        indicatorType = a.getInt(R.styleable.ViewPagerIndicator_indicator_type, 0);
        initPaint();
    }

    private void initPaint() {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        if (indicatorType == 0) {//指针的高度
            mPaint.setStrokeWidth(mNormalIndicatorHeight);
            mPaint.setColor(mNormalIndicatorColor);
        } else {
            mPaint.setColor(mNormalIndicatorColor);
        }
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setPathEffect(new CornerPathEffect(5));
    }

    /**
     * 绑定viewPager
     *
     * @param viewPager
     */
    public void setViewPager(ViewPager viewPager, int pos) {
        this.mViewPager = viewPager;
        initViewPager(pos);
    }

    /**
     * 设置标签集合
     *
     * @param list
     */
    public void setList(List<String> list) {
        this.mTitles = list;
        if (mTitles != null && mTitles.size() > 0) {
            this.removeAllViews();
            //动态添加view
            for (String title : mTitles) {
                addView(generateTextView(title));
            }
            onTabItemClickEvent();
        }
    }

    /**
     * 计算每个view的宽度
     *
     * @param title
     * @return
     */
    private View generateTextView(String title) {
        TextView tv = new TextView(getContext());
        LayoutParams lp = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        lp.weight = 0;
        lp.width = getScreenWidth() / mVisibleTabCount;
//        lp.width = ViewGroup.LayoutParams.WRAP_CONTENT;
        tv.setText(title);
//        tv.setPadding(8, 0, 8, 0);
        setNormalTextStyle(tv);
        tv.setLayoutParams(lp);
        return tv;
    }

    /**
     * 设置未选中标签的样式
     *
     * @param tv
     */
    private void setNormalTextStyle(TextView tv) {
        tv.setTextColor(mNormalTextColor);
        tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, mNormalTextSize);
        tv.setGravity(Gravity.CENTER);
    }

    /**
     * 将所有标签设置为初始未选中状态
     */
    private void resetTabStyle() {
        for (int i = 0; i < getChildCount(); i++) {
            TextView tv = (TextView) getChildAt(i);
            setNormalTextStyle(tv);
        }
    }

    /**
     * 设置选中标签的样式
     *
     * @param pos
     */
    private void setSelectedTextStyle(int pos) {
        resetTabStyle();
        View view = getChildAt(pos);
        if (view instanceof TextView) {
            TextView tv = (TextView) view;
            tv.setTextColor(mSelectTextColor);
            tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, mSelectTextSize);
            tv.setGravity(Gravity.CENTER);
        }
    }

    /**
     * 获取屏幕的宽度
     *
     * @return
     */
    private int getScreenWidth() {
        WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        int tabCount = getChildCount();
        if (tabCount == 0) return;

        for (int i = 0; i < tabCount; i++) {
            View view = getChildAt(i);
            LayoutParams lp = (LayoutParams) view.getLayoutParams();
            lp.weight = 0;
            lp.width = getScreenWidth() / mVisibleTabCount;
//            lp.width = ViewGroup.LayoutParams.WRAP_CONTENT;
            view.setLayoutParams(lp);
        }
        onTabItemClickEvent();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        //计算三角形的宽度
        mTriangleWidth = (int) (w / mVisibleTabCount * RADION_TRIANGLE_WIDTH_AND_HEIGHT);
        mTriangleMaxWidth = getHeight() / 3;
        mTriangleWidth = Math.min(mTriangleWidth, mTriangleMaxWidth);
        //计算初始的偏移位置
        mFirstTranslationX = w / mVisibleTabCount / 2 - mTriangleWidth / 2;
        initTriangle();
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        canvas.save();
        if (indicatorType == 0) {
            //下划线
            canvas.drawLine(mTranslationX, getHeight(), mTranslationX + getWidth() / mVisibleTabCount, getHeight(), mPaint);
//            canvas.drawLine(mTranslationStartX, getHeight(), mTranslationEndX, getHeight(), mPaint);
        } else {
            //三角形
            canvas.translate(mTranslationX + mFirstTranslationX, getHeight() + 2);
            canvas.drawPath(mPath, mPaint);
        }
        canvas.restore();
        super.dispatchDraw(canvas);
    }

    /**
     * 指示器跟随手指滑动
     *
     * @param position
     * @param offset
     */
    private void scroll(int position, float offset) {
        //获取一个标签的宽度
        int tabWidth = getWidth() / mVisibleTabCount;
        //手指滑动过程中的偏移量
        mTranslationX = (int) (tabWidth * (position + offset));
        //整体位移
        if (position >= (mVisibleTabCount - 2) && offset > 0 &&
                getChildCount() > mVisibleTabCount && position < getChildCount() - 2) {
            if (mVisibleTabCount != 1) {
                this.scrollTo((position - (mVisibleTabCount - 2)) * tabWidth + (int) (tabWidth * offset), 0);
            } else {
                this.scrollTo(position * tabWidth + (int) (tabWidth * offset), 0);
            }
        }
        invalidate();
    }

//    /**
//     * 指示器跟随手指滑动
//     *
//     * @param position
//     * @param offset
//     */
//    private void scroll(int position, float offset) {
//        int x = 0;
//        for (int i = 0; i < position; i++) {
//            x += getChildAt(i).getWidth();
//        }
//
//        if (position < getChildCount()) {
//            mTranslationStartX = mTranslationX = (int) (x + offset * getChildAt(position).getWidth());
//            mTranslationEndX = x + (int) (getChildAt(position + 1).getWidth() * offset) + getChildAt(position).getWidth();
//        }
//        if (x + getChildAt(position).getWidth() + getChildAt(position + 1).getWidth() > getScreenWidth()) {
//            this.scrollTo(mTranslationEndX, 0);
//        }
//        invalidate();
//    }

    /**
     * 绘制三角形
     */
    private void initTriangle() {
        mTriangleHeight = mTriangleWidth / 2;
        mPath = new Path();
        mPath.moveTo(0, 0);
        mPath.lineTo(mTriangleWidth, 0);
        mPath.lineTo(mTriangleWidth / 2, -mTriangleHeight);
        mPath.close();
    }

    private void onTabItemClickEvent() {
        int tabCount = getChildCount();

        for (int i = 0; i < tabCount; i++) {
            final int j = i;
            View view = getChildAt(i);
            view.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    mViewPager.setCurrentItem(j);
                }
            });
        }
    }

    private void initViewPager(int pos) {
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//                mCurrentPosition = position;
                scroll(position, positionOffset);
            }

            @Override
            public void onPageSelected(int position) {
                setSelectedTextStyle(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mViewPager.setCurrentItem(pos);
        setSelectedTextStyle(pos);
    }

}
